package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.admin.entity.WhStockOut;
import com.dingreading.cloud.admin.entity.WhStockOutDelivery;
import com.dingreading.cloud.admin.entity.WhStockOutDeliveryImg;
import com.dingreading.cloud.admin.service.WhStockOutDeliveryImgService;
import com.dingreading.cloud.admin.service.WhStockOutDeliveryService;
import com.dingreading.cloud.admin.service.WhStockOutService;
import com.dingreading.cloud.admin.util.bean.PurchaseUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.LocalFileUtil;
import com.dingreading.cloud.common.util.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/stockOutDelivery")
@Api(tags = "总部-出库补发货管理")
public class WhStockOutDeliveryController {

    @Resource
    protected WhStockOutDeliveryService stockOutDeliveryService;
    @Resource
    protected WhStockOutService stockOutService;
    @Resource
    protected WhStockOutDeliveryImgService stockOutDeliveryImgService;


    @ApiOperation(value = "删除")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "仓库id") @RequestParam(value = "id") Long id
    ) {
        WhStockOutDelivery data = stockOutDeliveryService.getById(id);
        if (data == null) return R.fail("获取失败");

        boolean day = TimeUtil.moreThanDay(data.getAddTime(), 30);
        if (day)
            return R.fail("添加已超过30天不能删除");

        stockOutDeliveryService.removeById(id);

        return R.ok();
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "添加/修改发货信息")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "发货记录id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "出库订单号") @RequestParam(value = "outCode") String outCode,
            @ApiParam(value = "快递公司") @RequestParam(value = "expressName") String expressName,
            @ApiParam(value = "快递单号") @RequestParam(value = "expressCode", required = false) String expressCode,
            @ApiParam(value = "快递费用") @RequestParam(value = "expressPrice", required = false) Double expressPrice,
            @ApiParam(value = "揽收时间") @RequestParam(value = "expressTime", required = false) String expressTime,
            @ApiParam(value = "快递费用到付 1.公司支付 2.到付 3.自提 4.包邮") @RequestParam(value = "expressPayType", required = false) Integer expressPayType,
            @ApiParam(value = "包裹数量") @RequestParam(value = "packageNum", required = false) Integer packageNum,
            @ApiParam(value = "发货仓库id") @RequestParam(value = "deliveryWarehouseId", required = false) Long deliveryWarehouseId,
            @ApiParam(value = "发货仓库名称") @RequestParam(value = "deliveryWarehouseName", required = false) String deliveryWarehouseName,
            @ApiParam(value = "物流单图片 [id:0,url:'']") @RequestParam(value = "imgJson", required = false) String imgJson,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark
    ) throws Exception {
        WhStockOut stockOut = stockOutService.getByOutCode(outCode);
        if (stockOut == null) return R.fail("出库订单获取失败");

        // 新增/修改发货记录
        WhStockOutDelivery data = null;
        if (id != null && id > 0) {
            data = stockOutDeliveryService.getById(id);
            if (data == null)
                return R.fail("获取失败");
            boolean day = TimeUtil.moreThanDay2(data.getAddTime(), 30);
            if (day)
                return R.fail("添加已超过30天不能修改");
        }

        data = PurchaseUtil.newStockOutDelivery(
                data, headStaffUid, headStaffName, 2, outCode, stockOut.getOrderCode(), stockOut.getStockOutMethod(),
                stockOut.getName(), stockOut.getPhone(), stockOut.getAddress(),
                expressName, expressCode, expressPrice, expressPayType, expressTime, packageNum,
                deliveryWarehouseId, deliveryWarehouseName, remark
        );
        stockOutDeliveryService.saveBean(data);

        if (id != null && id > 0) {
            if (StringUtils.isNotBlank(imgJson)) {
                List<WhStockOutDeliveryImg> imgList = JSONArray.parseArray(imgJson, WhStockOutDeliveryImg.class);
                if (CollectionUtils.isNotEmpty(imgList)) {
                    List<Long> updateIdList = new ArrayList<>();
                    List<WhStockOutDeliveryImg> newList = new ArrayList<>();
                    for (WhStockOutDeliveryImg img : imgList) {
                        if (img.getId() == null || img.getId() <= 0) {
                            img.setDeliveryId(data.getId());
                            newList.add(img);
                        } else {
                            updateIdList.add(img.getId());
                        }
                    }
                    // 删除不要的图片
                    List<WhStockOutDeliveryImg> deleteImgList = stockOutDeliveryImgService.listByImgIdNotIn(data.getId(), updateIdList);
                    if (CollectionUtils.isNotEmpty(deleteImgList)) {
                        // 删除本地图片集合
                        List<String> urlList = deleteImgList.stream().map(WhStockOutDeliveryImg::getUrl).collect(Collectors.toList());
                        LocalFileUtil.deleteImgList(LocalFileUtil.orderFormBaseDir, urlList);

                        stockOutDeliveryImgService.deleteByImgIdNotIn(data.getId(), updateIdList);
                    }
                    // 保存
                    stockOutDeliveryImgService.saveOrUpdateBatch(newList);
                }
            } else {
                // 删除全部的图片
                List<WhStockOutDeliveryImg> deleteImgList = stockOutDeliveryImgService.listByDeliveryId(data.getId());
                if (CollectionUtils.isNotEmpty(deleteImgList)) {
                    // 删除本地图片集合
                    List<String> urlList = deleteImgList.stream().map(WhStockOutDeliveryImg::getUrl).collect(Collectors.toList());
                    LocalFileUtil.deleteImgList(LocalFileUtil.orderFormBaseDir, urlList);

                    stockOutDeliveryImgService.deleteByDeliveryId(data.getId());
                }
            }
        } else {
            if (StringUtils.isNotBlank(imgJson)) {
                List<WhStockOutDeliveryImg> imgList = JSONArray.parseArray(imgJson, WhStockOutDeliveryImg.class);
                if (CollectionUtils.isNotEmpty(imgList)) {
                    for (WhStockOutDeliveryImg img : imgList) {
                        img.setDeliveryId(data.getId());
                    }
                    stockOutDeliveryImgService.saveOrUpdateBatch(imgList);
                }
            }
        }

        return R.ok();
    }


}
